# src/api/transaction_api.py
from flask import Blueprint, request, jsonify
from src.service.transaction_service import (
    create_order,
    pay_order,
    cancel_order,
    confirm_receipt,
    get_buyer_orders
)
from src.utils.logger import get_logger

transaction_bp = Blueprint("transaction", __name__, url_prefix="/api/transaction")
logger = get_logger(__name__)

@transaction_bp.route("/create", methods=["POST"])
def create():
    """创建订单（购买艺术品）"""
    try:
        data = request.get_json()
        buyer_id = data.get("buyer_id")
        artwork_id = data.get("artwork_id")
        
        transaction_id, msg = create_order(buyer_id=buyer_id, artwork_id=artwork_id)
        
        if transaction_id:
            return jsonify({
                "success": True,
                "message": msg,
                "transaction_id": transaction_id
            }), 201
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"创建订单接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@transaction_bp.route("/<string:transaction_id>/pay", methods=["POST"])
def pay(transaction_id):
    """支付订单"""
    try:
        success, msg = pay_order(transaction_id=transaction_id)
        
        if success:
            return jsonify({"success": True, "message": msg}), 200
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"支付订单接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@transaction_bp.route("/<string:transaction_id>/cancel", methods=["POST"])
def cancel(transaction_id):
    """取消订单"""
    try:
        success, msg = cancel_order(transaction_id=transaction_id)
        
        if success:
            return jsonify({"success": True, "message": msg}), 200
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"取消订单接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@transaction_bp.route("/<string:transaction_id>/confirm", methods=["POST"])
def confirm(transaction_id):
    """确认收货"""
    try:
        success, msg = confirm_receipt(transaction_id=transaction_id)
        
        if success:
            return jsonify({"success": True, "message": msg}), 200
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"确认收货接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

@transaction_bp.route("/buyer/<int:buyer_id>", methods=["GET"])
def get_buyer_transactions(buyer_id):
    """获取买家订单列表"""
    try:
        status = request.args.get("status")  # 可选参数：筛选状态
        transactions, msg = get_buyer_orders(buyer_id=buyer_id, status=status)
        
        return jsonify({
            "success": True,
            "count": len(transactions),
            "transactions": transactions
        }), 200
    except Exception as e:
        logger.error(f"获取买家订单接口异常：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500